package com.jds.test.http;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.List;

/**
 * Created by sunyuming on 18/8/30.
 */
public class RequestToBodyDecoder extends MessageToMessageDecoder<FullHttpRequest> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List<Object> list) throws Exception {
        // 内存泄漏 fullHttpRequest不再往下传递了，传递的是json
        //   ByteBuf msg = fullHttpRequest.content().retain();
        ByteBuf msg = fullHttpRequest.content();

        byte[] bs = new byte[msg.readableBytes()];
        msg.readBytes(bs);
        String json = new String(bs);

        JSONObject jsonObject = null;

        try {
            jsonObject = JSONObject.parseObject(json);
        } catch (Exception e) {
            System.out.println("json error:" + json);

            ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(ResponseMessage.genFail());
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(!future.isSuccess()) {
                        future.cause().printStackTrace();
                        future.channel().close();
                    }
                }
            });
            return;
        }

        if(null == jsonObject)
            jsonObject = new JSONObject();

        // 这样逻辑更通些
        // channelHandlerContext.fireChannelRead(jsonObject);
        // 这样也行，但是逻辑和性能都不如前者
        // super.channelRead(channelHandlerContext, jsonObject);

        list.add(jsonObject);
    }
}
